package com.hz.friends.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVGeoPoint;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FunctionCallback;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.GroupChatActivity;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.serverrequest.ALCCPEngine.ALGroupType;
import com.hz.friends.serverrequest.ALEngineConfig.ALUserGender;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SkipFansActivity extends BaseActivity{
	private int type = -3; // 0:my fans 我的粉丝 1:my concern 互相关注 2:black list 拉黑
	private PullToRefreshListView mlistview;
	private AQuery aq;
	private MediaPlayer mMediaPlayer = new MediaPlayer();
	private NearByUserAdpter adpter;
	private final int limit = 100;// 分页
	private int skip = 0;// 跳过记录条数
	private TextView txv_nodata;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_skipfans);
		init();
		initactionbar();
		initViews();
		initEvents();
		onRefresh();
 
	}
	
	@Override
	protected void init() {
 		type = getIntent().getIntExtra("type", 0);
		aq = new AQuery(this);

	}
	private void initactionbar() {
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_right.setVisibility(View.INVISIBLE);
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		imbtn_bar_left.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setResult(0);  
               finish();				
			}
		});
		
		switch (type) {
		case 0:
			imbtn_bar_title.setText("Fans");
			break;
		case 1:
			imbtn_bar_title.setText("Concern");
			break;
		case 2:
			imbtn_bar_title.setText("Blcaklist");
			break;
		default:
			break;
		}
	}
	@Override
	protected void initViews() {
		txv_nodata = (TextView)findViewById(R.id.txv_nodata);
		mlistview = (PullToRefreshListView)findViewById(R.id.mlistview);
		adpter = new NearByUserAdpter(this);
		mlistview.setAdapter(adpter);
	}

	@Override
	protected void setViews() {
		
	}

	@Override
	protected void initEvents() {
		mlistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {

			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				onRefresh();
			}
		});
		mlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//                CustomApplication.getInstance().currgroup = madpter.getItem(position-1);
//				Intent intent = new Intent(mcontext,GroupChatActivity.class);
//				intent.putExtra("titlename",  madpter.getItem(position-1).getString("name"));
//				intent.putExtra("isGroup", true);
//				mcontext.startActivity(intent);
                
			}
		});
	}
	
	private void onRefresh() {
		createWiatDialog("加载中");
		txv_nodata.setVisibility(View.GONE);
		skip = 0;
		adpter.clearData();
		switch (type) {
		case 0:
			uploadFolloweeList();
			uploadFriends1();
			break;
		case 1:
			uploadFolloweeList();
			uploadFriends2();
			break;
		case 2:
			uploadFriends3();
			break;
		default:
			break;
		}
	}
	
	// 我的粉丝
	private void uploadFriends1() {
		ALUserEngine.defauleEngine().getFollowerList(AVUser.getCurrentUser(),
				limit, skip, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadFriends1 avexception:" + avexception
								+ "  object:" + object);
						mlistview.onRefreshComplete();
						cancleWaitDialog();
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;
							if (data == null || data.size() == 0) {
								txv_nodata.setVisibility(View.VISIBLE);
							} else {
								skip = skip + data.size();
								adpter.addData(data);
								adpter.notifyDataSetChanged();
							}
					 
						} else {
							avexception.printStackTrace();
							showSysToast("请求失败");
						}

					}
				});

	}


	// 互粉
	private void uploadFriends2() {
		ALUserEngine.defauleEngine().getFolloweeAndFollowerList(
				AVUser.getCurrentUser(), limit, skip, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadFriends3 avexception:" + avexception
								+ "  object:" + object);
						cancleWaitDialog();
						mlistview.onRefreshComplete();
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;
							if (data == null || data.size() == 0) {
								txv_nodata.setVisibility(View.VISIBLE);
							} else {
								skip = skip + data.size();
								adpter.addData(data);
								adpter.notifyDataSetChanged();
								adpter.addFollowData(data);
							}
						} else {
							avexception.printStackTrace();
							showSysToast("请求失败");
						}

					}
				});

	}
	
	// 拉黑名单
	private void uploadFriends3() {
		ALUserEngine.defauleEngine().getMyBanList(limit, skip, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadFriends3 avexception:" + avexception
								+ "  object:" + object);
						cancleWaitDialog();
						mlistview.onRefreshComplete();
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;
							if (data == null || data.size() == 0) {
								txv_nodata.setVisibility(View.VISIBLE);
							} else {
								skip = skip + data.size();
								adpter.addData(data);
								adpter.notifyDataSetChanged();
							}
						} else {
							avexception.printStackTrace();
							showSysToast("请求失败");
						}

					}
				});

	}
	
	// 我的关注
	private void uploadFolloweeList() {
		ALUserEngine.defauleEngine().getFolloweeList(AVUser.getCurrentUser(),
				100, 0, new CallBack() {
					@Override
					public void done(Object object, AVException avexception) {

						MLog.i(TAG, "uploadFolloweeList avexception:"
								+ avexception + "  object:" + object);
						mlistview.onRefreshComplete();
						if (avexception == null) {
							HashMap<String, List> map = (HashMap<String, List>) object;
							if (map == null) {
//								if (madpter.getCount() == 0) {
//									// ((MaintabsActivity) mcontext)
//									// .showSysToast("没有好友");
//								} else
//									((MaintabsActivity) mcontext)
//											.showSysToast("没有更多");
								return;
							}
							List<AVUser> data = map.get("followees");
							if (data == null || data.size() == 0) {
//								if (madpter.getCount() == 0) {
//									// ((MaintabsActivity) mcontext)
//									// .showSysToast("没有好友");
//								} else
//									((MaintabsActivity) mcontext)
//											.showSysToast("没有更多");
								
								return;
							}
							 adpter.addFollowData(data);
						} else {
							avexception.printStackTrace();
//							((MaintabsActivity) mcontext).showSysToast("请求错误");
						}

					}
				});
	}
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(mMediaPlayer != null){
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
	class NearByUserAdpter extends BaseAdapter {
		private List<AVUser> userlist = new ArrayList<AVUser>();
		private List<AVUser> followlist = new ArrayList<AVUser>();
		private Context mcontext;
		private AQuery aq ;
		@Override
		public int getCount() {
			return userlist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}
        
		public NearByUserAdpter(Context context){
			this.mcontext = context;
			aq = new AQuery(mcontext);
		}
		@Override
		public long getItemId(int position) {
			return 0;
		}

		public void setData(List<AVUser> userlist) {
			if (userlist == null)
				return;
			this.userlist = userlist;
			// loadFriendAttents();
		}

		public void addData(List<AVUser> userlist) {
			if (userlist == null)
				return;
			this.userlist.addAll(userlist);
			this.notifyDataSetChanged();
		}

		public void addFollowData(List<AVUser> userlist) {
			if (userlist == null)
				return;
			this.followlist.addAll(userlist);
		}

		public void clearData() {
			this.userlist.clear();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(mcontext).inflate(
						R.layout.adpter_nearbyusers, null);
				// holder = new ViewHolder();
				holder.imv_heard = (ImageView) convertView
						.findViewById(R.id.imv_heard);
				holder.txv_name = (TextView) convertView
						.findViewById(R.id.txv_name);
				holder.btn_special = (Button) convertView
						.findViewById(R.id.btn_special);
				holder.layoutxx = (LinearLayout) convertView
						.findViewById(R.id.layoutxx);
				holder.txv_signature = (TextView) convertView
						.findViewById(R.id.txv_signature);
				holder.layout_sex = (LinearLayout) convertView
						.findViewById(R.id.layout_sex);
				holder.imv_sex = (ImageView) convertView
						.findViewById(R.id.imv_sex);
				holder.txv_age = (TextView) convertView
						.findViewById(R.id.txv_age);
				holder.layout_voice = (LinearLayout) convertView
						.findViewById(R.id.layout_voice);
				holder.txv_voiceduration = (TextView) convertView
						.findViewById(R.id.txv_voiceduration);
				holder.imv_speakanim = (ImageView) convertView
						.findViewById(R.id.imv_speakanim);
				holder.txv_durationkm = (TextView) convertView
						.findViewById(R.id.txv_durationkm);
				holder.txv_timeafter = (TextView) convertView
						.findViewById(R.id.txv_timeafter);
				
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final AVUser avuser = userlist.get(position);
			String name = avuser.getUsername();
			final String nickname = avuser.getString("nickname");
			String heardurl = avuser.getString("headViewURL");
			String signature = avuser.getString("signature");
			if(TextUtils.isEmpty(signature))
				signature ="No content";
			Date brithday = avuser.getDate("brithday");
			int gender = avuser.getInt("gender");
			int introductionOfVoiceOfDuration = avuser
					.getInt("introductionOfVoiceOfDuration");
			final String introductionOfVoiceURL = avuser
					.getString("introductionOfVoiceURL");
			AVGeoPoint togeopoint = avuser.getAVGeoPoint("location");
			 Date togeopointdate = avuser.getDate("lastUpdateLocationDate");


			final int width = DensityUtil.dip2px(mcontext, 70);
			// default image
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					mcontext, crclebitmap, width, 1, "#eeeeee");
			holder.imv_heard.setImageBitmap(crclestrokebitmap);

			aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
				@Override
				public void callback(String url, Bitmap bitmap,
						AjaxStatus status) {
					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(mcontext,
							bitmap, width, 1, "#eeeeee");
					holder.imv_heard.setImageBitmap(mbitmap);
				}
			});
			holder.txv_name.setText(nickname);
			holder.txv_signature.setText(signature);
			holder.txv_age.setText(String.valueOf(UtilTools
					.getAgeByBirthday(brithday))); // 年龄
			setDistance(togeopoint, holder.txv_durationkm);
			if(togeopointdate != null){
				holder.txv_timeafter.setText(UtilTools.getdurtionTimeFormat(togeopointdate, new Date()));
			}else{
				holder.txv_timeafter.setText("no time");
			}
			holder.imv_heard.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					((CustomApplication) ((Activity) mcontext).getApplication()).user = avuser;
					Bundle bundle = new Bundle();
					bundle.putInt("isother", 1);
					Intent intent = new Intent(mcontext,
							UserInfosActivity.class);
					intent.putExtras(bundle);
					mcontext.startActivity(intent);
				}
			});
			holder.layoutxx.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					CustomApplication.getInstance().user = avuser;
					Intent intent = new Intent(mcontext,
							GroupChatActivity.class);
					intent.putExtra("titlename", nickname);
					intent.putExtra("isGroup", false);
					mcontext.startActivity(intent);
				}
			});
			holder.btn_special.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					addFriend(avuser, holder.btn_special);
				}
			});
			if (gender == ALUserGender.ALUserGenderOfFemale.get_value()) {// 女性
				holder.layout_sex
						.setBackgroundResource(R.drawable.shape_bj_icwoman_xml);
				holder.imv_sex.setImageResource(R.drawable.ic_woman);
			} else {// 男性
				holder.layout_sex
						.setBackgroundResource(R.drawable.shape_bj_icman_xml);
				holder.imv_sex.setImageResource(R.drawable.ic_man);
			}

			getAttenState(avuser, holder.btn_special);

			// 语音
			if (introductionOfVoiceOfDuration > 0) {
				holder.layout_voice.setVisibility(View.VISIBLE);
				holder.txv_voiceduration.setText(String
						.valueOf(introductionOfVoiceOfDuration) + "\'\'");
				holder.txv_voiceduration.setTag(introductionOfVoiceURL);
			} else {
				holder.layout_voice.setVisibility(View.INVISIBLE);
			}

			holder.layout_voice.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					playMusic(introductionOfVoiceURL, holder.imv_speakanim);
				}
			});
			
			if(type == 3)
			{
				holder.btn_special.setVisibility(View.INVISIBLE);
			}else{
				holder.btn_special.setVisibility(View.VISIBLE);
			}			
			return convertView;
		}

		private void setDistance(AVGeoPoint togeopoint,TextView txv) {
			AVGeoPoint mgeopoint = AVUser.getCurrentUser().getAVGeoPoint("location");
			if(mgeopoint == null || togeopoint == null){
				txv.setText("unknow");
				return;
			}
			double distan = mgeopoint.distanceInKilometersTo(togeopoint);
			  DecimalFormat  df = new DecimalFormat("#.##");
				double km = distan/1000;
			   txv.setText(df.format(km)+" km");
			
		}
		
		private void addFriend(final AVUser avuser,final Button btn) {
			if (btn.getTag() != null){//移除关注
				ALUserEngine.defauleEngine().removeFollow(avuser,
						new CallBack() {

							@Override
							public void done(Object object, AVException avexception) {
								if (avexception == null) {
									showSysToast("取消关注成功");
									btn.setText("Attention");
									btn.setBackgroundResource(R.drawable.shape_nearby_attention);
									btn.setTag(null);
								} else {
									showSysToast("取消关注失败");
									avexception.printStackTrace();
								}
							}
						});
			}else{//添加关注
				ALUserEngine.defauleEngine().addFollow(avuser,null,
						new CallBack() {

							@Override
							public void done(Object object, AVException avexception) {
								if (avexception == null) {
									showSysToast("关注成功");
									btn.setText("Cancel");
									btn.setBackgroundResource(R.drawable.shape_nearby_attention2);
									btn.setTag("1");
								} else {
									showSysToast("关注失败");
									avexception.printStackTrace();
								}
							}
						});
			}
		

		}

		private void getAttenState(AVUser avuser,  Button btn) {
			for (int i = 0; i < this.followlist.size(); i++) {
				AVUser user = this.followlist.get(i);
				if (avuser.getObjectId().equals(user.getObjectId())) {
					btn.setText("Cancel");
					btn.setBackgroundResource(R.drawable.shape_nearby_attention2);
					btn.setTag("1");
					return;
				}
			}
			btn.setText("Attention");
			btn.setBackgroundResource(R.drawable.shape_nearby_attention);
			btn.setTag(null);

		}

	}

	private static class ViewHolder {
		ImageView imv_heard; //
		TextView txv_name;//
		LinearLayout layoutxx;
		Button btn_special;
		TextView txv_signature; // 签名
		LinearLayout layout_sex; // 性别布局
		ImageView imv_sex; // 性别图标
		TextView txv_age; // 年龄
		LinearLayout layout_voice;// 声音
		TextView txv_voiceduration; // 声音
		ImageView imv_speakanim; // 声音动画
		TextView txv_durationkm; // 距离
		TextView txv_timeafter; // 距离更新时间
		
	}
	/**
	 * @Description
	 * @param name
	 */
	private void playMusic(final String url, final ImageView iv_voice) {
		try {
			synchronized (mMediaPlayer) {// 清除上条消息的状态
				if (mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
				}
				iv_voice.setVisibility(View.VISIBLE);
				final AnimationDrawable voiceAnimation = (AnimationDrawable) iv_voice
						.getDrawable();
				mMediaPlayer.reset();
				mMediaPlayer.setDataSource(url);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
				voiceAnimation.start();
				mMediaPlayer
						.setOnCompletionListener(new OnCompletionListener() {
							public void onCompletion(MediaPlayer mp) {
								voiceAnimation.stop();
								iv_voice.setVisibility(View.INVISIBLE);
							}
						});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	

}
